package cn.yeziji.netty.adapter;

import cn.yeziji.forum.basic.netty.chat.ChatMessage;
import cn.yeziji.forum.basic.netty.user.UserMessage;
import cn.yeziji.netty.config.handler.NettyWebsocketHandler;
import cn.yeziji.netty.entity.ChatUserChannelMessage;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * 退出公共聊天室适配器
 *
 * @author gzkemays
 * @since 2022/11/09 11:37 PM
 */
@Slf4j
public class PublicChatExitAdapter extends SelectedTypes<ChatMessage>
    implements CommunicationAdapters {
  NettyWebsocketHandler nettyWebsocketHandler = getNettyWebsocketHandler();

  public PublicChatExitAdapter(Integer type, String text) {
    super(type, text, ChatMessage.class);
    //    this.data = JSON.parseObject(text, ChatMessage.class);
  }

  @Override
  public void notice(ChannelHandlerContext channelHandlerContext) {
    // 删除聊天室中的用户
    List<ChatUserChannelMessage> publicChatList = nettyWebsocketHandler.getPublicChatList();
    Map<ChannelHandlerContext, UserMessage> connectUserMsg =
        nettyWebsocketHandler.getConnectUserMsg();
    // 获取离开用户的信息
    UserMessage leaveUser = connectUserMsg.get(channelHandlerContext);
    for (ChatUserChannelMessage chatUserChannelMessage : publicChatList) {
      // 把离开用户的信息发送给客户端
      log.info(
          "通知 {} 用户 {} 离开了",
          chatUserChannelMessage.getMessage().getNickname(),
          leaveUser.getNickname());
      if (data == null) {
        data = new ChatMessage();
        data.setFrom(leaveUser);
      }
      writeAndFlush(chatUserChannelMessage.getContext(), data);
    }
    publicChatList.removeIf(c -> c.getContext().equals(channelHandlerContext));
    log.info("还有 {} 用户在公共聊天室", publicChatList.size());
  }

  @Override
  public Object dispose(ChannelHandlerContext channelHandlerContext) {
    return null;
  }
}
